package com.biscuit.page.basicservice.design.search.strategy;

import com.biscuit.page.basicservice.api.model.response.search.SearchSuggestAResp;
import com.biscuit.page.basicservice.design.search.SearchHandlerContext;
import com.biscuit.page.basicservice.model.dto.search.SearchSuggest360DTO;
import com.biscuit.page.basicservice.utils.HttpUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author biscuit
 * @createTime 2024/6/6 11:15
 */
public class V360SearchHandlerStrategy implements SearchHandlerStrategy {

    private SearchHandlerContext context;

    @Override
    public List<SearchSuggestAResp.SuggestAResp> suggest() {
        // 向 360 请求关联词的请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("encodein", "utf-8");
        paramMap.put("encodeout", "utf-8");
        paramMap.put("format", "json");
        paramMap.put("fields", "word");
        paramMap.put("word", context.getKeyword());

        // 调用 360 的搜索接口，获取联想词列表
        SearchSuggest360DTO suggestDTO = HttpUtil.get(context.getSearchEngineTypeEnum().getSourceUrl(), paramMap, SearchSuggest360DTO.class);

        // 结果非空判断
        if (Objects.isNull(suggestDTO)) {
            return new ArrayList<>();
        }

        // 将 DTO 转换为响应所需格式，并返回结果
        return suggestDTO.getResult().stream().map(x -> {
            SearchSuggestAResp.SuggestAResp data = new SearchSuggestAResp.SuggestAResp();
            data.setText(x.getWord());
            data.setRedirectUrl(context.getSearchEngineTypeEnum().getTargetUrl() + "?q=" + data.getText());
            return data;
        }).collect(Collectors.toList());
    }

    @Override
    public void setContext(SearchHandlerContext context) {
        this.context = context;
    }
}
